<style lang="scss" scoped>
    .warning-messages{

    }
  .warningBall{
    color:#fff;
    display: inline-block;
    width:20px;
    height:20px;
    line-height: 20px;
    font-size:18px;
    text-align: center;
    border-radius: 10px;
  }
  .content_bottom{
    height: calc(100vh - 215px);
  }
  .table_h{height: calc(100vh - 470px);}
</style>
<template>
  <div class='warning-messages'>
    <el-row class="main-box" style="padding:10px;margin:10px 0;">
      <el-col :span='4'>
        <el-switch
          style="margin-top:8px;"
          active-color="#409eff"
          inactive-color="#409eff"
          @change="resetData()"
          v-model="listType"
          active-text="最新告警"
          inactive-text="历史记录">
        </el-switch>
      </el-col>
      <remote-data style="width:100%;" :sendObj="searchFactor1" :otherConfig="{hasEmpty:true}"></remote-data>
      <div class="label_desc" v-if="!listType">处理状态：</div>
      <el-col :span='2' v-if="!listType">
        <el-select v-model="searchFactor.status" clearable  placeholder="请选择">
          <el-option label="未处理" :value="0"></el-option>
          <el-option label="已忽略" :value="1"></el-option>
          <el-option label="已上报" :value="2"></el-option>
          <el-option label="已处理" :value="3"></el-option>
        </el-select>
      </el-col>
      <div class="label_desc" v-if="!listType">告警时间：</div>
     	<el-col :span='6' v-if="!listType">
		    <el-col :span="12">
		    	<el-date-picker class="wd100" value-format="yyyy-MM-dd HH:mm:ss" v-model="searchFactor.modify_start_time" type="date" placeholder="开始时间" :editable="false"></el-date-picker>
		    </el-col>
        <el-col :span="12">
          <el-date-picker class="wd100 ml10" value-format="yyyy-MM-dd HH:mm:ss" v-model="searchFactor.modify_end_time" type="date"  placeholder="结束时间" :editable="false"></el-date-picker>
        </el-col>
    </el-col> 
     <div>
      <el-button style="margin-left:12px;" type="primary" @click.native.prevent="getTableData();page=1">搜索</el-button>
      <el-button  style="margin-left:2px;" @click.native.prevent="resetData()" class="cancel_btn">重置</el-button>
      <el-button type="danger" v-if="!listType && buttonPageObj['warningInfo.delete']" @click.native.prevent="deleteBatch">批量删除</el-button>
    </div>
  	</el-row>
    <el-row class="content_bottom" ref="tableWrapper">
      <warningTable
              ref="warningTable"
              :tableData="tableData"
              :tableHeight="tableHeight"
              :listType="listType"
              @clickItem="clickItem"
              @deleteItem="deleteItem">
      </warningTable>
      <el-pagination v-if="tableData.length > 0" class="page_sub" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
                     :page-sizes="[10,20,30,40,50,60,100,200,500]"
                     :page-size="size"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
      <no-data v-if="tableData.length == 0"></no-data>
		</el-row>
      <warning-detail v-if="showModal" :showModal.sync="showModal" :status="getStatus" :currentData="currentData" @update="updateStatus"></warning-detail>
  </div>
</template>
<script>

    import {mapGetters} from "vuex"

export default {
	name:'warningMessage',
	components: {
      remoteData: () => import('./remoteData')
	},
  data() {
  	let _this = this;
    return {
      showModal:false,
      tableHeight:null,
      currentData:{},
      //  Table 配置start
      searchFactor: {
        projectId:_this.$route.params.projectId||"",
        type: 'alert_level',
        level:'',
        status:'',
        modify_start_time:'',
        modify_end_time:'',
      },
      searchFactor1:{
        projectId:''
      },
      tableData: [],
      page:1,
      size:60,
      total:0,

      pieOptions:null,
      barOptions:null,
      levelColor : ['#e40000','#ff8a00','#ffde00','#1482f0'],
      numletters : ['一','二','三','四'],
      listType:true
    };
  },
  watch:{
  	'$route'(){
  		if(this.$route.name=='warningInfo'){
  			this.getPageData();
  		}
  	}
  },
  activated(){
    let _this = this;
    window.onresize = function(){
      console.log(1)
      _this.tableHeight = _this.$refs.tableWrapper.$el.offsetHeight - 66
    }
  },
  deactivated(){
	  window.onresize = null
  },
  destroyed(){
	  window.onresize = null
  },
  mounted(){
    console.log(this.$route.params)
  	let _this = this;
    this.tableHeight = this.$refs.tableWrapper.$el.offsetHeight - 66
    window.onresize = function(){
      console.log(1)
      _this.tableHeight = _this.$refs.tableWrapper.$el.offsetHeight - 66
    }
    this.$Bus.$on('clickPie', function (params) {
      _this.searchFactor.level = params.data.level
      _this.page = 1
      _this.listType = false
      _this.getTableData();
    })
   	this.$Bus.$on('clickBar', function (params) {
      _this.searchFactor.proj_id = params.data.projectId
      _this.searchFactor.level = params.data.level
      _this.page = 1
      _this.listType = false
      _this.getTableData();
    })
    if(this.$route.params.projectCode && this.$route.params.pointId){
      this.getPieChartData();
      this.getBarChartData();
      if(this.$route.params.historyData) {
        this.listType = false
        let sendobj = {
          "andCondition": {
            "projectId": this.$route.params.projectCode || "",
            "pointId": this.$route.params.pointId
          },
            "orderByCondition": {"time":"desc"},
          "pageObj":{
            "current":this.page,
            "size":this.size
          }
        }
        this.$httpProj.post("alert/alertData/listPage", sendobj).then(res => {
            this.tableData = res.data.list
            this.total = res.data.totalElements
        })
      }else{
        this.listType = true
        let sendobj = {
          "andCondition": {
            "projectId": this.$route.params.projectCode || "",
            "pointId": this.$route.params.pointId
          },
            "orderByCondition": {"time":"desc"},
          "pageObj":{
            "current":this.page,
            "size":this.size
          }
        }
        this.$httpProj.post("alert/alertData/findLastListByPage",sendobj).then(res => {
          this.tableData = res.data.list
          this.total = res.data.totalElements
        })
      }
    }else {
      this.getPageData();
    }
  },
  computed:{
    getStatus(){
      switch(this.currentData.status){
        case 0:
          return '未处理'
          break
        case 1:
          return '已忽略'
          break;
        case 2:
          return '已上报'
          break;
        case 3:
          return '已处理'
          break;
      }
    },
      ...mapGetters([
          'buttonPageObj'
      ])
  },
  methods:{
    getType(type){
      switch(type){
        case 1:
          return '阈值'
          break
        case 2:
          return '趋势'
          break;
        case 3:
          return '突变'
          break;
        case 4:
          return '关联'
          break;
        case 5:
          return '预警'
          break;
      }
    },
    updateStatus(data){
      this.getTableData()
      this.showModal = false
    },
    handleSizeChange(size){
      this.size = size;
      this.page = this.page;
      this.getTableData()
    },
    handleCurrentChange(page){
      this.page = page;
      this.size = this.size;
      this.getTableData()
    },
    clickItem(item) {
      this.showModal = true;
      this.currentData = item
    },
    deleteItem(item) {
      this.$confirm('确定删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$httpProj.delete("alert/alertData/" + item.id).then(res => {
          this.getTableData()
          this.$message({
            type: 'success',
            message: '删除成功！'
          })
        })
      })
    },
      deleteBatch() {
            const ids = this.$refs.warningTable.multipleSelection.map(item => item.id)
          if(ids.length == 0) {
              this.$message({
                  type:'warning',
                  message:'请勾选需要删除的数据'
              })
              return false
          }
          this.$confirm('确定删除吗？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
          }).then(() => {
              this.$httpProj.post("/alert/alertData/deleteBatch?noProjectId=1",ids).then(res => {
                  this.getTableData()
                  this.$message({
                      type: 'success',
                      message: '删除成功！'
                  })
              })
          })
      },
    getTableData(){
      if(this.listType){
        let sendobj = {
          "andCondition": {
            "projectId": this.searchFactor1.projectId?this.searchFactor1.projectId:"",
          },
          "inCondition":{
            "status":[0,2]
          },
            "orderByCondition": {"time":"desc"},
          "pageObj": {
            "current": this.page,
            "size": this.size
          }
        }
        this.$httpProj.post("alert/alertData/listPage", sendobj).then(res => {
          this.tableData = res.data.list
          this.total = res.data.totalElements
        })
      }else {
        let sendobj = {
          "andCondition": {
            "projectId": this.searchFactor1.projectId?this.searchFactor1.projectId:"",
            "status": this.searchFactor.status
          },
          "otherCondition": {
            "level": this.searchFactor.level
          },
          "gtCondition": this.searchFactor.modify_start_time ? {
            "time": this.searchFactor.modify_start_time
          } : {},
          "ltCondition": this.searchFactor.modify_end_time ? {
            "time": this.searchFactor.modify_end_time
          } : {},
            "orderByCondition": {"time":"desc"},
          "pageObj": {
            "current": this.page,
            "size": this.size
          }
        }
        this.$httpProj.post("alert/alertData/listPage", sendobj).then(res => {
            this.tableData = res.data.list
            this.total = res.data.totalElements
        })
      }
    },
  	getPageData(){
      this.getTableData();
      this.getPieChartData();
      this.getBarChartData();
  	},
    /*加载饼图*/
  	getPieChartData() {
      //获取bar的数据
      let getPieData =() => {
        return new Promise((resolve, reject) => {
          this.$httpProj.get("alert/alertData/infoLevelStatistic").then(res => {
            resolve(res.data)
          }).catch(() => {
            reject()
          })
        })
      }
      getPieData().then(res => {
        let data = res.map((item) => {
          item = {value:item.num, name:this.numletters[item.level - 1]+'级',level:item.level,itemStyle:{color:this.levelColor[item.level - 1]}}
          return item
        })
        this.initPieChart(data)
      }).catch((res => {

      }))
  	},
    initPieChart(data){
      let option = {
        title : {
          text: '预警级别占比',
          x:'center',
          textStyle:{
            fontSize:14
          }
        },
        tooltip : {
          trigger: 'item',
          formatter: "{b} : {c} ({d}%)",
          position: function(point, params, dom, rect, size){
            //其中point为当前鼠标的位置，size中有两个属性：viewSize和contentSize，分别为外层div和tooltip提示框的大小
            var x = point[0];//
            var y = point[1];
            var viewWidth = size.viewSize[0];
            var viewHeight = size.viewSize[1];
            var boxWidth = size.contentSize[0];
            var boxHeight = size.contentSize[1];
            var posX = 0;//x坐标位置
            var posY = 0;//y坐标位置

            if(x<boxWidth){//左边放不开
              posX = 5;
            }else{//左边放的下
              posX = x-boxWidth;
            }

            if(y<boxHeight){//上边放不开
              posY = 5;
            }else{//上边放得下
              posY = y-boxHeight;
            }
            return [posX,posY];
          }
        },
        series : [
          {
            type: 'pie',
            radius : '65%',
            center: ['50%', '60%'],
            data:data,
            label: {
              formatter: '{b}:{c}({d}%)'
            },
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      this.pieOptions = option;
    },
    /*加载柱状图*/
    getBarChartData() {
      //获取bar的数据
      let getBarData =() => {
        return new Promise((resolve, reject) => {
          this.$httpProj.get("alert/alertData/infoLevelStatisticGroupByProject").then(res => {
            if (res.status = 200) {
              resolve(res.data)
            } else {
              reject()
            }
          }).catch(() => {
            reject()
          })
        })
      }
      getBarData().then(res => {
        let _this = this
        let data = res
        let xAxis = data.map(item => item.projectName)
        xAxis = new Set(xAxis)
        xAxis = [...xAxis]

        let series = [{
          level:1,
          name:'一级',
          type: 'bar',
          barMaxWidth:'40',
          barWidth:'40%',
          stack: '预警',
          data:new Array(xAxis.length).fill(0).map((item) => {
            return {
              value: 0,
              projectId:'',
              level:1,
              itemStyle: {
                color: this.levelColor[0]
              }
            }
          })
        },{
          level:2,
          name:'二级',
          type: 'bar',
          barMaxWidth:'40',
          barWidth:'40%',
          stack: '预警',
          data:new Array(xAxis.length).fill(0).map((item) => {
            return {
              value: 0,
              level:2,
              projectId:'',
              itemStyle: {
                color: this.levelColor[1]
              }
            }
          })
        },{
          level:3,
          name:'三级',
          type: 'bar',
          barMaxWidth:'40',
          barWidth:'40%',
          stack: '预警',
          data:new Array(xAxis.length).fill(0).map((item) => {
            return {
              level:3,
              value: 0,
              projectId:'',
              itemStyle: {
                color: this.levelColor[2]
              }
            }
          })
        },{
          level:4,
          name:'四级',
          type: 'bar',
          barMaxWidth:'40',
          barWidth:'40%',
          stack: '预警',
          data:new Array(xAxis.length).fill(0).map((item) => {
            return {
              value: 0,
              level:4,
              projectId:'',
              itemStyle: {
                color: this.levelColor[3]
              }
            }
          })
        }]

        for(let i = 0;i<xAxis.length;i++){
          for(let j=0;j<data.length;j++){
            if(data[j].projectName == xAxis[i]) {
              series[data[j].level - 1].data[i].value = data[j].num
              series[data[j].level - 1].data[i].projectId = data[j].projectId
            }
          }
        }

        let ret = {
          xAxis :xAxis,
          series : series
        }

        console.log(ret)

        this.initBarChart(ret)
      }).catch((res => {

      }))
    },
    initBarChart(data){
      let option = {
        title : {
          text: '预警级别项目分布',
          x:'center',
          textStyle:{
            fontSize:14
          }
        },
        tooltip : {
          trigger: 'axis',
          axisPointer : {            // 坐标轴指示器，坐标轴触发有效
            type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
          },
          position: function(point, params, dom, rect, size){
            //其中point为当前鼠标的位置，size中有两个属性：viewSize和contentSize，分别为外层div和tooltip提示框的大小
            var x = point[0];//
            var y = point[1];
            var viewWidth = size.viewSize[0];
            var viewHeight = size.viewSize[1];
            var boxWidth = size.contentSize[0];
            var boxHeight = size.contentSize[1];
            var posX = 0;//x坐标位置
            var posY = 0;//y坐标位置

            if(x<boxWidth){//左边放不开
              posX = 5;
            }else{//左边放的下
              posX = x-boxWidth;
            }

            if(y<boxHeight){//上边放不开
              posY = 5;
            }else{//上边放得下
              posY = y-boxHeight;
            }
            return [posX,posY];
          }
        },
        grid: {
          top:'20',
          left: '1%',
          right: '1%',
          bottom: '1%',
          containLabel: true
        },
        xAxis:  {
          type: 'category',
          data: data.xAxis,
          axisLabel : {
            showMaxLabel: true //展示x轴最后一条数据
          },
          axisTick: {
            inside: true,
            lignWithLabel: true //这两行代码可以让刻度正对刻度名
          },
          boundaryGap: true,//两边是否留白
        },
        yAxis: {
          type: 'value',
          axisTick: {
            show: false
          }
        },
        dataZoom : [{
          type: 'inside',  //鼠标滚轮
          realtime : true,
        }],
        series: data.series
      }
      this.barOptions = option;
    },
  	resetData(){
      this.page = 1
      this.searchFactor = {
        projectId: this.$route.params.projectId || '',
        type: 'alert_level',
        level: '',
        status: '',
        message: '',
        modify_start_time: '',
        modify_end_time: '',
      }
      this.searchFactor1 = {
        projectId:''
      }
  		this.getTableData();
  	}
  }
};
</script>
